package handler

import (
	"2302a/tiktok_business/api/request"
	"2302a/tiktok_business/api/resp"
	"2302a/tiktok_business/global"
	"2302a/tiktok_business/internal/dao"
	"2302a/tiktok_business/internal/model"
	"context"
	"github.com/gin-gonic/gin"
	"net/http"
	"time"
)

func AddVideo(c *gin.Context) {
	var req request.AddVideo
	err := c.ShouldBind(&req)
	if err != nil {
		resp.Error(c, http.StatusUnauthorized, "参数信息错误", err.Error())
		return
	}
	var user model.Users
	userId := c.GetUint("userId")
	dao.GetOneById(c.GetUint("userId"), &user)

	parse, _ := time.Parse(time.DateTime, req.PublishTime)

	videos := model.Videos{
		UserId:      userId,
		Title:       req.Title,
		Description: req.Description,
		VideoUrl:    req.VideoUrl,
		CoverUrl:    req.CoverUrl,
		RegionTag:   req.RegionTag,
		PublishTime: parse,
		Duration:    req.Duration,
		PlayCount:   req.PlayCount,
	}
	dao.Create(&videos)
	resp.Success(c, "发布视频成功", true)

}

func ListVideo(c *gin.Context) {
	var req request.ListVideo
	err := c.ShouldBind(&req)
	if err != nil {
		resp.Error(c, http.StatusUnauthorized, "参数信息错误", err.Error())
		return
	}
	var video []model.Videos
	page := req.Page
	if page <= 0 {
		page = 1
	}

	pageSize := req.PageSize
	switch {
	case pageSize > 100:
		pageSize = 100
	case pageSize <= 0:
		pageSize = 5
	}
	offset := (page - 1) * pageSize
	global.DB.Offset(offset).Limit(pageSize).Find(&video)
	resp.Success(c, "视频分页成功", video)
}

func StatusVideo(c *gin.Context) {
	var req request.StatusVideo
	err := c.ShouldBind(&req)
	if err != nil {
		resp.Error(c, http.StatusUnauthorized, "参数信息错误", err.Error())
		return
	}
	var video model.Videos
	global.DB.Find(&video)
	if video.VideoId == 0 {
		resp.Error(c, http.StatusUnauthorized, "视频不存在", false)
		return
	}

	if req.PlayCount == 1 {
		resp.Error(c, http.StatusUnauthorized, "未播放", false)
		return
	} else if req.PlayCount == 2 {
		resp.Success(c, "已播放30%", true)
	}

}

func BrowseVideo(c *gin.Context) {
	var video model.Videos
	global.DB.Find(&video)
	if video.VideoId == 0 {
		resp.Error(c, http.StatusUnauthorized, "视频不存在", false)
		return
	}

	var listVideo []model.Videos
	dao.GetListByField(&model.Videos{Title: video.Title}, &listVideo)
	global.DB.Order("created_at").Find(&listVideo)
	global.RDB.Set(context.Background(), "browse"+video.Title, listVideo, time.Hour*1)
	resp.Success(c, "最近的 10 条", listVideo)
}

func SearchVideo(c *gin.Context) {
	var req request.SearchVideoReq
	err := c.ShouldBind(&req)
	if err != nil {
		resp.Error(c, http.StatusUnauthorized, "参数信息错误", err.Error())
		return
	}
	var videos []model.Videos
	page := req.Page
	if page <= 0 {
		page = 1
	}

	pageSize := req.PageSize
	switch {
	case pageSize > 100:
		pageSize = 100
	case pageSize <= 0:
		pageSize = 5
	}
	offset := (page - 1) * pageSize
	global.DB.Offset(offset).Limit(pageSize).Find(&videos)
	global.DB.Where("region_tag like ?", "%"+req.RegionTag+"%").Find(&videos)
	resp.Success(c, "展示该地区成功", videos)

}
